/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * <h2><center>&copy; Copyright (c) 2020 STMicroelectronics.
  * All rights reserved.</center></h2>
  *
  * This software component is licensed by ST under BSD 3-Clause license,
  * the "License"; You may not use this file except in compliance with the
  * License. You may obtain a copy of the License at:
  *                        opensource.org/licenses/BSD-3-Clause
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "dma.h"
#include "fatfs.h"
#include "i2c.h"
#include "sai.h"
#include "sdmmc.h"
#include "spi.h"
#include "usart.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
//https://github.com/simonschmidt/hobby-stm32scope
#include	"stdio.h"
#include	"math.h"
#include	"Record_WAV.h"
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
#define		WM8960_RECORD_TEST		1
/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
extern	uint8_t I2S_Callback_Flag;
extern  uint8_t I2S_Half_Callback_Flag;
/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */
//#define		AUDIO_RATE_HZ		16000
//#define 	WAV_BUFFER_SIZE 	64000
////uint8_t 	WAV_Buffer[WAV_BUFFER_SIZE];  //The buffer to ache WAV data
//int16_t 	WAV_Buffer[WAV_BUFFER_SIZE] = {0};  //The buffer to ache WAV data

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */
uint8_t 	WM8960_Init_Record(void);
void 		Strat_Record(void);
void 		SDIO_Test(void);
/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
uint32_t	g_main_cnt = 0;
int16_t		g_record_cnt = 0;
extern 		  uint8_t WAV_Buffer_Record[WAV_BUFFER_SIZE];
/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{
  /* USER CODE BEGIN 1 */
	uint8_t res;
	int32_t	i;
  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_DMA_Init();
  MX_I2C1_Init();
  MX_SAI3_Init();
  MX_UART4_Init();
  MX_USART6_UART_Init();
  MX_SPI4_Init();
  MX_SDMMC2_SD_Init();
  MX_FATFS_Init();
  /* USER CODE BEGIN 2 */

  HAL_GPIO_WritePin(USER_LED1_GPIO_Port, USER_LED1_Pin, GPIO_PIN_SET);
  HAL_GPIO_WritePin(USER_LED2_GPIO_Port, USER_LED2_Pin, GPIO_PIN_SET);
  HAL_GPIO_WritePin(USER_LED3_GPIO_Port, USER_LED3_Pin, GPIO_PIN_SET);
  HAL_GPIO_WritePin(USER_LED4_GPIO_Port, USER_LED4_Pin, GPIO_PIN_SET);

  HAL_GPIO_WritePin(GPIOC, WIFI_3VEN_Pin|USER_LED1_Pin, GPIO_PIN_SET);

  printf("System initial finished.\n");

  for(i=0;i<15;i++)
  {
	  HAL_Delay(200);
	  HAL_GPIO_TogglePin(USER_LED3_GPIO_Port, USER_LED3_Pin);
  }
  HAL_GPIO_WritePin(USER_LED3_GPIO_Port, USER_LED3_Pin, GPIO_PIN_SET);


//  printf("Start SDIO_Test().\n");
//   SDIO_Test();


//  retSD = f_mount(&SDFatFS, (TCHAR const*)SDPath, 0);
  retSD = f_mount(&SDFatFS, "", 0);
  if(retSD != FR_OK)  {
	  printf("f_mount fail ! Error code: %d\r\n", retSD);
    while(1)  {
      HAL_Delay(1000);
    }
  }
  else
  {
    printf("f_mount completed !!\r\n");
  }


#if	WM8960_RECORD_TEST == 0
  //res = WM89060_Init();
#endif
#if WM8960_RECORD_TEST == 1
  res = WM8960_Init_Record();
#endif
  printf("WM89060_Init: %d\r\n", res);

//  printf_wm8960_regs();
//  printf_wm8960_regs_iic_read();

  Strat_Record();

  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
	  HAL_GPIO_TogglePin(USER_LED1_GPIO_Port, USER_LED1_Pin);

	  HAL_Delay(100);
	  g_main_cnt++;
	  if(g_main_cnt%10 == 0)
	  {
		  printf("g_main_cnt: %ld\n", g_main_cnt);
	  }
  }
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
  RCC_PeriphCLKInitTypeDef PeriphClkInitStruct = {0};

  /** Supply configuration update enable
  */
  HAL_PWREx_ConfigSupply(PWR_LDO_SUPPLY);
  /** Configure the main internal regulator output voltage
  */
  __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE0);

  while(!__HAL_PWR_GET_FLAG(PWR_FLAG_VOSRDY)) {}
  /** Macro to configure the PLL clock source
  */
  __HAL_RCC_PLL_PLLSOURCE_CONFIG(RCC_PLLSOURCE_HSI);
  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
  RCC_OscInitStruct.HSIState = RCC_HSI_DIV1;
  RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI;
  RCC_OscInitStruct.PLL.PLLM = 4;
  RCC_OscInitStruct.PLL.PLLN = 60;
  RCC_OscInitStruct.PLL.PLLP = 2;
  RCC_OscInitStruct.PLL.PLLQ = 8;
  RCC_OscInitStruct.PLL.PLLR = 2;
  RCC_OscInitStruct.PLL.PLLRGE = RCC_PLL1VCIRANGE_3;
  RCC_OscInitStruct.PLL.PLLVCOSEL = RCC_PLL1VCOWIDE;
  RCC_OscInitStruct.PLL.PLLFRACN = 0;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }
  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2
                              |RCC_CLOCKTYPE_D3PCLK1|RCC_CLOCKTYPE_D1PCLK1;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.SYSCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_HCLK_DIV2;
  RCC_ClkInitStruct.APB3CLKDivider = RCC_APB3_DIV2;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_APB1_DIV2;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_APB2_DIV2;
  RCC_ClkInitStruct.APB4CLKDivider = RCC_APB4_DIV2;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_4) != HAL_OK)
  {
    Error_Handler();
  }
  PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_UART4|RCC_PERIPHCLK_USART6
                              |RCC_PERIPHCLK_SPI4|RCC_PERIPHCLK_SAI3
                              |RCC_PERIPHCLK_SDMMC|RCC_PERIPHCLK_I2C1;
  PeriphClkInitStruct.PLL2.PLL2M = 32;
  PeriphClkInitStruct.PLL2.PLL2N = 120;
  PeriphClkInitStruct.PLL2.PLL2P = 2;
  PeriphClkInitStruct.PLL2.PLL2Q = 2;
  PeriphClkInitStruct.PLL2.PLL2R = 6;
  PeriphClkInitStruct.PLL2.PLL2RGE = RCC_PLL2VCIRANGE_1;
  PeriphClkInitStruct.PLL2.PLL2VCOSEL = RCC_PLL2VCOWIDE;
  PeriphClkInitStruct.PLL2.PLL2FRACN = 0;
  PeriphClkInitStruct.SdmmcClockSelection = RCC_SDMMCCLKSOURCE_PLL2;
  PeriphClkInitStruct.Sai23ClockSelection = RCC_SAI23CLKSOURCE_PLL;
  PeriphClkInitStruct.Spi45ClockSelection = RCC_SPI45CLKSOURCE_D2PCLK1;
  PeriphClkInitStruct.Usart234578ClockSelection = RCC_USART234578CLKSOURCE_D2PCLK1;
  PeriphClkInitStruct.Usart16ClockSelection = RCC_USART16CLKSOURCE_D2PCLK2;
  PeriphClkInitStruct.I2c123ClockSelection = RCC_I2C123CLKSOURCE_D2PCLK1;
  if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInitStruct) != HAL_OK)
  {
    Error_Handler();
  }
}

/* USER CODE BEGIN 4 */

void HAL_SAI_RxHalfCpltCallback(SAI_HandleTypeDef *hsai)  {

  I2S_Half_Callback_Flag = 1;
  //printf("HAL_SAI_RxHalfCpltCallback.\r\n");

}

void HAL_SAI_RxCpltCallback(SAI_HandleTypeDef *hsai)  {

  I2S_Callback_Flag = 1;
  //printf("HAL_SAI_RxCpltCallback.\r\n");
  if(Rec_Flag == START_REC) {
    HAL_SAI_Receive_DMA(&hsai_BlockB3,WAV_Buffer, WAV_BUFFER_SIZE/2);
    HAL_SAI_Transmit_DMA(&hsai_BlockA3,(uint8_t*)WAV_BufferSend,  WAV_BUFFER_SIZE/2);
//    printf("HAL_SAI_Receive_DMA: %d\r\n", res);
  }
}


FIL MyFile;     /* File object */
int rest = 500;


void SDIO_Test(void)
{

	int i = 0;
  FRESULT res;                                          		/* FatFs function common result code */
  uint32_t byteswritten, bytesread;                     		/* File write/read counts */
  //uint8_t wtext[] = "This is STM32H750 working with FatFs"; 	/* File write buffer */
  uint8_t wtext[4096];
  TCHAR* fname = "STM32H750VB_BrdHogPi_20201125.TXT"; 						/* File Name */
  uint8_t rtext[4096];                                   		/* File read buffer */

  for(i=0;i<4096;i++)
  {
	  wtext[i] = 'A'+i%26;
  }


  if(f_mount(&SDFatFS, (TCHAR const*)SDPath, 0) != FR_OK)
	{
		/* FatFs Initialization Error */
	  printf("f_mount Err\r\n");
		Error_Handler();
	}
	else
	{
		/*##-4- Create and Open a new text file object with write access #####*/
		if(f_open(&MyFile, fname, FA_CREATE_ALWAYS | FA_WRITE) != FR_OK)
		{
			printf("f_open Err: %s, %d\r\n", __FILE__, __LINE__);
			Error_Handler();
		}
		else
		{
			/*##-5- Write data to the text file ################################*/
			res = f_write(&MyFile, wtext, sizeof(wtext), (void *)&byteswritten);

			if((byteswritten == 0) || (res != FR_OK))
			{
				printf("f_write Err: (byteswritten == 0) || (res != FR_OK)\r\n");
				Error_Handler();
			}
			else
			{
				/*##-6- Close the open text file #################################*/
				f_close(&MyFile);

				/*##-7- Open the text file object with read access ###############*/
				if(f_open(&MyFile, fname, FA_READ) != FR_OK)
				{
					printf("f_open Err: f_open(&MyFile, fname, FA_READ) != FR_OK \r\n");
					Error_Handler();
				}
				else
				{
					/*##-8- Read data from the text file ###########################*/
					res = f_read(&MyFile, rtext, sizeof(rtext), (UINT*)&bytesread);

					if((bytesread == 0) || (res != FR_OK)) /* EOF or Error */
					{
						printf("f_open Err: (bytesread == 0) || (res != FR_OK) \r\n");
						Error_Handler();
					}
					else
					{
						/*##-9- Close the open text file #############################*/
						f_close(&MyFile);

						/*##-10- Compare read data with the expected data ############*/
						if ((bytesread != byteswritten))
						{
							/* Read data is different from the expected data */
							printf("Read data is different from the expected data\r\n");
							Error_Handler();
						}
						else
						{
							/* Success of the demo: no error occurrence */
							printf("No error occurrence.\r\n Success of the Fatfs demo!!!\r\n");
							// BSP_LED_On(LED1);
							rest = 1000;
						}
					}
				}
			}
		}
	}
}





/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */

  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     tex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
